import _ from "lodash";
import fs from "fs";
import path from "path";
// 批量读取文件

type OnContent = (fileName: string, data: Buffer) => void;
type OnErr = (err: NodeJS.ErrnoException) => void;

// 读取一个文件夹中的文件
export function readFiles(
  dirname: string
): Promise<{ fileName: string; data: Buffer }[]> {
  return new Promise((res, rej) => {
    fs.readdir(dirname, (err, files) => {
      if (!_.isEmpty(err)) {
        rej(err);
      } else {
        let _res: { fileName: string; data: Buffer }[] = [];
        _.each(files, (file) => {
          fs.readFile(path.resolve(dirname, file), (err, data) => {
            if (!_.isEmpty(err)) rej(err);
            else {
              _res.push({ fileName: file, data: data });
              if (_res.length === files.length) {
                // 如果读取完成所有文件 resolve
                res(_res);
              }
            }
          });
        });
      }
    });
  });
}
